import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/cart_item.dart';
import '../models/product.dart';
import 'auth_service.dart';

class CartService {
  static const String _baseUrl = 'YOUR_API_BASE_URL';
  final AuthService _authService;
  final List<CartItem> _items = [];

  CartService(this._authService);

  List<CartItem> get items => List.unmodifiable(_items);

  double get totalAmount => _items.fold(0, (sum, item) => sum + item.totalPrice);

  Future<void> loadCart() async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/cart'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        _items.clear();
        _items.addAll(
          (data['items'] as List).map(
            (item) => CartItem(
              product: Product.fromJson(item['product']),
              quantity: item['quantity'],
            ),
          ),
        );
      }
    } catch (e) {
      // Handle error
    }
  }

  Future<bool> addToCart(CartItem item) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/cart'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
        body: jsonEncode({
          'productId': item.product.id,
          'quantity': item.quantity,
        }),
      );

      if (response.statusCode == 200) {
        _items.add(item);
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<bool> updateCartItem(CartItem item) async {
    try {
      final response = await http.put(
        Uri.parse('$_baseUrl/cart/${item.product.id}'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
        body: jsonEncode({
          'quantity': item.quantity,
        }),
      );

      if (response.statusCode == 200) {
        final index = _items.indexWhere((i) => i.product.id == item.product.id);
        if (index != -1) {
          _items[index] = item;
        }
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<bool> removeFromCart(String productId) async {
    try {
      final response = await http.delete(
        Uri.parse('$_baseUrl/cart/$productId'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        _items.removeWhere((item) => item.product.id == productId);
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<void> clearCart() async {
    try {
      final response = await http.delete(
        Uri.parse('$_baseUrl/cart'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        _items.clear();
      }
    } catch (e) {
      // Handle error
    }
  }
} 